﻿using LocalNas.Application.Service.Wankeyun;

namespace LocalNas.Application.Job;

public class JobWorker : ISpareTimeWorker
{

    [SpareTime(100, "AppStart", Description = "服务启动时触发", StartNow = true, DoOnce = true, ExecuteType = SpareTimeExecuteTypes.Serial)]
    public async void AppStart(SpareTimer timer, long count)
    {
        await Scoped.CreateAsync(async (_s, scope) =>
        {
            var services = scope.ServiceProvider;
            var sysSettingRep = App.GetService<SqlSugarRepository<SysSetting>>(services);
            var setting = await sysSettingRep.GetFirstAsync(x => x.Key == ConstSettingKey.秀人网下载任务自动运行);
            if (!string.IsNullOrWhiteSpace(setting?.Value))
            {
                if (setting.Value.ToUpper() == "TRUE")
                {
                    SpareTime.Start("套图采集-秀人网");
                    await GlobalData.ReceiveMessage(new SendMessageData
                    {
                        Title = "成功",
                        Message = $"【套图采集-秀人网】定时任务已启动",
                        MessageType = MessageTypeEnum.通知
                    });
                }
            }

            try
            {
                await GlobalData.InitWky();
            }
            catch (Exception ex)
            {
                await GlobalData.ReceiveMessage(new SendMessageData
                {
                    Title = "异常",
                    Message = ex.Message,
                    MessageType = MessageTypeEnum.通知
                });
            }


            //var wankeyun = App.GetService<Module.Wankeyun.WankeyunApi>(services);
            //wankeyun.GetDevice();
        });
    }



    [SpareTime(3000, "套图采集-秀人网", Description = "自动采集秀人网套图", StartNow = false, DoOnce = false, ExecuteType = SpareTimeExecuteTypes.Serial)]
    public async void PicHunterJob(SpareTimer timer, long count)
    {
        await Scoped.CreateAsync(async (_s, scope) =>
          {
              SpareTime.Stop("套图采集-秀人网");
              var services = scope.ServiceProvider;
              ServicePointManager.Expect100Continue = true;
              ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
              // 解析其他服务
              var api = App.GetService<XrmnService>(services);
              var sysSettingRep = App.GetService<SqlSugarRepository<SysSetting>>(services);
              var setting = await sysSettingRep.GetFirstAsync(x => x.Key == ConstSettingKey.秀人网下载目录);
              if (setting == null || string.IsNullOrWhiteSpace(setting.Value))
              {
                  await GlobalData.ReceiveMessage(new SendMessageData
                  {
                      Title = "错误",
                      Message = $"请先设置{ConstSettingKey.秀人网下载目录}",
                      MessageType = MessageTypeEnum.通知
                  });
                  return;
              }
              var savePath = setting.Value;  //App.Configuration["PicHunter:Path"];

              #region 加载所有分类

              //var types = await api.GetTypes();
              //if (types == null)
              //{
              //    await ReceiveMessage(new SendMessageData
              //    {
              //        Title = "错误",
              //        Message = "图片分类获取失败",
              //        MessageType = MessageTypeEnum.日志
              //    });
              //    return;
              //}
              //
              //foreach (var type in types)
              //{
              //    if (type.TypeName != "XiuRen秀人网") continue;
              //    _ = PicHunterHandle(type, savePath);
              //}
              #endregion

              //加快采集，可以同时运行多个线程  默认从第一页开始采集
              _ = PicHunterHandle(new GetTypesResult { TypeName = "XiuRen秀人网", TypeUrl = "/XiuRen/" }, savePath);
              //_ = PicHunterHandle(new GetTypesResult { TypeName = "XiuRen秀人网", TypeUrl = "/XiuRen/" }, savePath, 50);
              //_ = PicHunterHandle(new GetTypesResult { TypeName = "XiuRen秀人网", TypeUrl = "/XiuRen/" }, savePath, 100);
              //_ = PicHunterHandle(new GetTypesResult { TypeName = "XiuRen秀人网", TypeUrl = "/XiuRen/" }, savePath, 150);

              _ = PicHunterHandle(new GetTypesResult { TypeName = "YouMi尤蜜荟", TypeUrl = "/YouMi/" }, savePath);
          });
    }





    private async Task PicHunterHandle(GetTypesResult type, string savePath, int startPage = 1)
    {
        await Scoped.CreateAsync(async (_s, scope) =>
        {
            var services = scope.ServiceProvider;
            var api = App.GetService<XrmnService>(services);
            //总页数
            var totalPage = await api.ListTotalPage(type);
            if (totalPage == 0) return;
            if (startPage > totalPage)
            {
                await GlobalData.ReceiveMessage(new SendMessageData
                {
                    Title = "错误",
                    Message = $"{type.TypeName}设定值({startPage})超过最大页数({totalPage})",
                    MessageType = MessageTypeEnum.日志
                });
                return;
            }
            savePath = Path.Combine(savePath, type.TypeName);
            for (int page = startPage; page <= totalPage; page++)
            {
                var list = await api.GetCoverList(type, page);
                if (list == null) continue;
                foreach (var item in list)
                {
                    var picCount = int.Parse(new Regex("\\d{1,3}(?=P)").Match(item.Title.ToUpper()).Value);
                    if (Directory.Exists(Path.Combine(savePath, item.Title)))
                    {
                        if (Directory.GetFiles(Path.Combine(savePath, item.Title)).Count() >= picCount)
                        {
                            await GlobalData.ReceiveMessage(new SendMessageData
                            {
                                Title = "跳过",
                                Message = item.Title,
                                MessageType = MessageTypeEnum.日志
                            });
                            continue;
                        }
                    }
                    await api.GetAllPicture(request: item, savePath, picCount);
                    //休息1分钟
                    await Task.Delay(5 * 1000);
                }
                //休息10分钟
                await Task.Delay(60 * 1000);
            }
        });
    }
}
